<template>
  <view class="park-map-container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">正在加载园区数据...</text>
    </view>
    
    <!-- 错误状态 -->
    <view v-else-if="error" class="error-container">
      <text class="error-text">{{ error }}</text>
      <button @click="retryLoad" class="retry-btn">重试</button>
    </view>
    
    <!-- 正常内容 -->
    <view v-else>
      <!-- 园区分布地图 -->
      <view class="map-section">
        <view class="shanghai-map-img-wrapper">
          <image src="/static/assets/park/park-map-bg.png" class="shanghai-map-img" mode="widthFix" />
        </view>
        <!-- 线路与标签一一对应布局 -->
        <view class="park-line-wrapper">
          <image v-if="areas[0] && areas[0].parks && areas[0].parks.length > 0"
            src="/static/assets/park/park-map-line-1.png" class="park-line-1" mode="widthFix" />
          <image v-if="areas[1] && areas[1].parks && areas[1].parks.length > 0"
            src="/static/assets/park/park-map-line-2.png" class="park-line-2" mode="widthFix" />
          <image v-if="areas[2] && areas[2].parks && areas[2].parks.length > 0"
            src="/static/assets/park/park-map-line-3.png" class="park-line-3" mode="widthFix" />
          <image v-if="areas[4] && areas[4].parks && areas[4].parks.length > 0"
            src="/static/assets/park/park-map-line-4.png" class="park-line-4" mode="widthFix" />
          <image v-if="areas[3] && areas[3].parks && areas[3].parks.length > 0"
            src="/static/assets/park/park-map-line-5.png" class="park-line-5" mode="widthFix" />
        </view>
        <view class="park-source-icon-wrapper">
          <view class="park-source-icon-1" :class="{ 'park-source-active': selectedAreaIndex === 0 }"
            v-if="areas[0] && areas[0].parks && areas[0].parks.length > 0" @click="handleSourceClick(0)">
            <image src="/static/assets/park/park-map-source.png" mode="widthFix" class="park-map-icon-img" />
          </view>
          <view class="park-source-icon-2" :class="{ 'park-source-active': selectedAreaIndex === 1 }"
            v-if="areas[1] && areas[1].parks && areas[1].parks.length > 0" @click="handleSourceClick(1)">
            <image src="/static/assets/park/park-map-source.png" mode="widthFix" class="park-map-icon-img" />
          </view>
          <view class="park-source-icon-3" :class="{ 'park-source-active': selectedAreaIndex === 2 }"
            v-if="areas[2] && areas[2].parks && areas[2].parks.length > 0" @click="handleSourceClick(2)">
            <image src="/static/assets/park/park-map-source.png" mode="widthFix" class="park-map-icon-img" />
          </view>
          <view class="park-source-icon-4" :class="{ 'park-source-active': selectedAreaIndex === 3 }"
            v-if="areas[3] && areas[3].parks && areas[3].parks.length > 0" @click="handleSourceClick(3)">
            <image src="/static/assets/park/park-map-source.png" mode="widthFix" class="park-map-icon-img" />
          </view>
          <view class="park-source-icon-5" :class="{ 'park-source-active': selectedAreaIndex === 4 }"
            v-if="areas[4] && areas[4].parks && areas[4].parks.length > 0" @click="handleSourceClick(4)">
            <image src="/static/assets/park/park-map-source.png" mode="widthFix" class="park-map-icon-img" />
          </view>
        </view>
        <!-- 区域标签，和线路一一对应 -->
        <view class="district-labels">
          <!-- 1号线对应标签 -->
          <view v-if="areas[0] && areas[0].parks && areas[0].parks.length > 0" class="district-label district-label-1">
            <text class="district-title">{{ areas[0].areaName }}</text>
            <view class="district-list">
              <text v-for="park in areas[0].parks" :key="park.id" @click="handleParkClick(park)">{{ park.parkName }}</text>
            </view>
          </view>
          <!-- 2号线对应标签 -->
          <view v-if="areas[1] && areas[1].parks && areas[1].parks.length > 0" class="district-label district-label-2">
            <text class="district-title">{{ areas[1].areaName }}</text>
            <view class="district-list">
              <text v-for="park in areas[1].parks" :key="park.id" @click="handleParkClick(park)">{{ park.parkName }}</text>
            </view>
          </view>
          <!-- 3号线对应标签 -->
          <view v-if="areas[2] && areas[2].parks && areas[2].parks.length > 0" class="district-label district-label-3">
            <text class="district-title">{{ areas[2].areaName }}</text>
            <view class="district-list">
              <text v-for="park in areas[2].parks" :key="park.id" @click="handleParkClick(park)">{{ park.parkName }}</text>
            </view>
          </view>
          <!-- 4号线对应标签 -->
          <view v-if="areas[3] && areas[3].parks && areas[3].parks.length > 0" class="district-label district-label-4">
            <text class="district-title">{{ areas[3].areaName }}</text>
            <view class="district-list">
              <text v-for="park in areas[3].parks" :key="park.id" @click="handleParkClick(park)">{{ park.parkName }}</text>
            </view>
          </view>
          <!-- 5号线对应标签 -->
          <view v-if="areas[4] && areas[4].parks && areas[4].parks.length > 0" class="district-label district-label-5">
            <text class="district-title">{{ areas[4].areaName }}</text>
            <view class="district-list">
              <text v-for="park in areas[4].parks" :key="park.id" @click="handleParkClick(park)">{{ park.parkName }}</text>
            </view>
          </view>
        </view>
        <view class="park-center-wrapper">
          <image src="/static/assets/park/park-map-center-tip.png" class="center-marker" />
          <text class="center-title">现代物流大厦</text>
        </view>
      </view>

      <!-- 园区图片与信息卡片 -->
      <view class="park-info-section">
        <image :src="park.thumbnailUrl || '/static/assets/park/park-defauter-avatar.png'" class="park-main-img" mode="aspectFill" />
        <view class="park-detail-card">
          <text class="park-title">{{ park.parkName || '请选择园区' }}</text>
          <view class="park-info-grid">
            <view class="info-item">
              <view class="info-icon-inner">
                <image src="/static/assets/park/park-icon-area.png" class="info-icon" />
              </view>
              <view class="info-text">
                <view class="info-label">占地面积</view>
                <view class="info-value">{{ park.totalArea  || '-'}}m²</view>
              </view>
            </view>
            <view class="info-item">
              <view class="info-icon-inner">
                <image src="/static/assets/park/park-icon-rarea.png" class="info-icon" />
              </view>
              <view class="info-text">
                <view class="info-label">建筑面积</view>
                <view class="info-value">{{ park.buildingArea  || '-'}}m²</view>
              </view>
            </view>
            <view class="info-item">
              <view class="info-icon-inner">
                <image src="/static/assets/park/park-icon-type.png" class="info-icon" />
              </view>
              <view class="info-text">
                <view class="info-label">仓库类型</view>
                <view class="info-value">{{park.warehouseTypes && park.warehouseTypes.map(item => item.typeName).join(',')  || '-'}}</view>
              </view>
            </view>
            <view class="info-item">
              <view class="info-icon-inner">
                <image src="/static/assets/park/park-icon-fheight.png" class="info-icon" />
              </view>
              <view class="info-text">
                <view class="info-label">层高</view>
                <view class="info-value">{{ park.floorHeight  || '-'}}</view>
              </view>
            </view>
            <view class="info-item">
              <view class="info-icon-inner">
                <image src="/static/assets/park/park-icon-rprice.png" class="info-icon" />
              </view>
              <view class="info-text">
                <view class="info-label">租赁单价</view>
                <view class="info-value">{{ park.rentalPrice || '-'}}元/m²/天</view>
              </view>
            </view>
            <view class="info-item">
              <view class="info-icon-inner">
                <image src="/static/assets/park/park-icon-rrate.png" class="info-icon" />
              </view>
              <view class="info-text">
                <view class="info-label">消防等级</view>
                <view class="info-value">{{ park.fireLevel || '-'}}</view>
              </view> 
            </view>
          </view>
        </view>
        <view class="primary-btn" @tap="goParkDetail">查看详情</view>
      </view>
    </view>
  </view>
</template>
<script>
import { API } from '@/utils/api.js'
import { processImageUrls } from '@/utils/url-helper.js'

export default {
  data() {
    return {
      park: {},
      selectedAreaIndex: 0,
      selectedParkIndex: 0,
      // 区域与园区数据
      areas: [],
      // 旧演示数据保留（未使用）
      markers: [],
      parks: [],
      // 加载状态
      loading: true,
      error: null
    }
  },
  async onLoad() {
    console.log('ParkMap页面开始加载...')
    await this.fetchAreaList()
  },
  methods: {
	  onShareAppMessage(res) {
	    console.log("onShareAppMessage", res);
	    return {
	      title: '百联物流',
	      path: '/pages/parkMap/parkMap',
	      imageUrl: '/static/sourceInfo/source-bottom-share.png'
	    }
	  },
	  onShareTimeline(res) {
	    console.log("onShareTimeline", res);
	  },
    handleParkClick(park) {
      console.log('选择园区:', park)
      this.park = processImageUrls(park)
      // this.goParkDetail()
    },
    async fetchAreaList() {
      try {
        this.loading = true
        this.error = null
        console.log('开始获取园区区域列表...')
        
        const res = await API.park.getAreaList({})
        console.log('API响应:', res)
        
        const list = Array.isArray(res?.data) ? res.data : (Array.isArray(res) ? res : [])
        console.log('处理后的列表:', list)
        
        // 目标顺序：id为6放0，9放1，11放2，8放3，7放4，其他顺序不变
        const idOrder = [6, 9, 11, 8, 7]
        const orderedAreas = []
        idOrder.forEach((id, idx) => {
          const found = list.find(item => String(item.id) === String(id))
          if (found) {
            orderedAreas[idx] = found
          } else {
            // id为空时插入空对象
            orderedAreas[idx] = {}
          }
        })
        // 追加剩余未排序的区域
        const usedIds = idOrder.map(String)
        list.forEach(item => {
          if (!usedIds.includes(String(item.id))) {
            orderedAreas.push(item)
          }
        })
        this.areas = orderedAreas
        console.log('排序后的区域:', this.areas)
        
        this.setDefaultSelection()
        this.loading = false
        
        console.log("最终park数据:", this.park);
        console.log("最终areas数据:", this.areas);
      } catch (e) {
        console.error('获取园区区域列表失败', e)
        this.loading = false
        this.error = '数据加载失败: ' + (e.message || '未知错误')
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        })
      }
    },
    setDefaultSelection() {
      if (!Array.isArray(this.areas) || this.areas.length === 0) {
        console.log('没有可用的区域数据')
        return
      }
      
      const firstArea = this.areas[0] || {}
      const parkList = firstArea.parks || firstArea.parkList || firstArea.list || []
      
      if (!Array.isArray(parkList) || parkList.length === 0) {
        console.log('第一个区域没有园区数据')
        return
      }
      
      this.selectedAreaIndex = 0
      this.selectedParkIndex = 0
      console.log("第一个区域的园区列表:", parkList);
      
      const p = parkList[0] || {}
      // 兼容字段名，统一到UI展示所需
      const mapStr = (v, fallback = '-') => {
        if (v === 0) return '0'
        return v ? String(v) : fallback
      }
      this.park = processImageUrls(p)
      console.log("设置默认园区:", this.park);
    },
    goParkDetail() {
      if (!this.park.parkId) {
        uni.showToast({
          title: '请先选择园区',
          icon: 'none'
        })
        return
      }
      uni.navigateTo({ 
        url: '/pages/parkMap/parkDetail?parkId=' + this.park.parkId + '&bannerPages=' + (this.park.bannerPages || '') 
      })
    },
    handleSourceClick(index) {
      console.log('点击区域:', index)
      this.selectedAreaIndex = index
      this.setDefaultSelection()
    },
    retryLoad() {
      this.fetchAreaList()
    }
  }
}
</script>
<style scoped>
.park-map-container {
  background: #ffffff;
  padding-bottom: 80rpx;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 400rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

/* 错误状态样式 */
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  padding: 40rpx;
}

.error-text {
  font-size: 28rpx;
  color: #ff4757;
  margin-bottom: 20rpx;
  text-align: center;
}

.retry-btn {
  background: #007aff;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 16rpx 32rpx;
  font-size: 26rpx;
}

.map-section {
  position: relative;
  padding: 97rpx 0 82rpx 0;
  align-items: center;
  justify-content: center;
}

.shanghai-map-img-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 522rpx;
  height: 600rpx;
  margin-left: auto;
  margin-right: auto;
}

.shanghai-map-img {
  width: 522rpx;
  height: 552rpx;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

.district-labels {
  position: absolute;
  inset: 0;
}

/* 1号线对应标签 */
.district-label-1 {
  top: 60rpx;
  left: 40rpx;
}

/* 2号线对应标签 */
.district-label-2 {
  top: 120rpx;
  right: 40rpx;
}

/* 3号线对应标签 */
.district-label-3 {
  bottom: 200rpx;
  right: 30rpx;
}

/* 4号线对应标签 */
.district-label-4 {
  bottom: 80rpx;
  left: 30rpx;
}

/* 5号线对应标签 */
.district-label-5 {
  bottom: 20rpx;
  right: 60rpx;
}

.district-label {
  position: absolute;
  background: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.06);
  padding: 12rpx 16rpx;
  max-width: 220rpx;
}

.district-title {
  color: #C02C38;
  font-size: 20rpx;
  font-weight: 700;
}

.district-list {
  margin-top: 8rpx;
  background: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
  border: 2rpx solid #eee;
}

.district-list text {
  display: block;
  padding: 6rpx 12rpx;
  font-size: 16rpx;
  color: #333;
}

.district-list text+text {
  border-top: 2rpx solid #f0f0f0;
}

.center-label {
  position: absolute;
  left: 50%;
  top: 52%;
  transform: translate(-50%, -50%);
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.park-center-wrapper {
  position: absolute;
  bottom: 250rpx;
  left: 310rpx;
  /* transform: translate(-50%, -50%); */
  display: flex;
  align-items: center;
  flex-direction: column;
  gap: 8rpx;
}

  .center-marker {
    width: 22rpx;
    height: 22rpx;
  }

.center-title {
  color: #333;
  font-size: 14rpx;
}

.park-info-section {
  /* padding: 24rpx; */
  border-radius: 16rpx;
  overflow: hidden;
}

.park-main-img {
  width: 100%;
  height: 300rpx;
  object-fit: contain;
  display: block;
}

.park-detail-card {
  margin-top: 24rpx;
  background: #ffffff;
  border-radius: 16rpx;
  padding: 24rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.06);
}

.park-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #222;
}

.park-info-grid {
  margin-top: 20rpx;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx 10rpx;
}

.info-item {
  display: grid;
  grid-template-columns: 80rpx 1fr;
  align-items: center;
  gap: 16rpx;
}

.info-icon-inner {
  width: 66rpx;
  height: 66rpx;
  background-image: url('/static/assets/park/park-icon-bg.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: center;
}

.info-icon {
  width: 32rpx;
  height: 32rpx;
  padding: 20rpx;
}

.info-text {}

.info-label {
  font-size: 22rpx;
  color: #3f3f3f6f;
}

.info-value {
  margin-top: 6rpx;
  font-size: 24rpx;
  font-weight: 700;
  color: #3f3f3f;
}

.primary-btn {
  margin: 24rpx;
  margin-top: 20rpx;
  height: 96rpx;
  background: #C02C38;
  color: #fff;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30rpx;
  font-weight: 700;
}

.park-line-wrapper {
  position: absolute;
  top: 100rpx;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.park-line-1 {
  position: absolute;
  top: 100rpx;
  left: 170rpx;
  width: 99rpx;
  height: 140rpx;
}

.park-line-2 {
  position: absolute;
  top: 100rpx;
  right: 150rpx;
  width: 252rpx;
  height: 138rpx;
}

.park-line-3 {
  position: absolute;
  top: 370rpx;
  right: 150rpx;
  width: 140rpx;
  height: 40rpx;
}

.park-line-4 {
  position: absolute;
  bottom: 180rpx;
  right: 200rpx;
  width: 164rpx;
  height: 112rpx;
}

.park-line-5 {
  position: absolute;
  bottom: 230rpx;
  left: 150rpx;
  width: 104rpx;
  height: 130rpx;
}

.park-source-icon-wrapper {
  position: absolute;
  top: 100rpx;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.park-source-icon-1 {
  position: absolute;
  top: 220rpx;
  left: 260rpx;
  pointer-events: none;
}

.park-source-icon-2 {
  position: absolute;
  top: 220rpx;
  left: 320rpx;
  pointer-events: none;
}

.park-source-icon-3 {
  position: absolute;
  top: 350rpx;
  right: 270rpx;
  pointer-events: none;
}

.park-source-icon-4 {
  position: absolute;
  bottom: 330rpx;
  left: 230rpx;
  pointer-events: none;
}

.park-source-icon-5 {
  position: absolute;
  bottom: 270rpx;
  right: 340rpx;
  pointer-events: none;
}

/* 下方演示列表与地图容器（保持现有结构） */
.container {
  padding: 24rpx;
}

.map {
  width: 100%;
  height: 400rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.park-card {
  margin-top: 24rpx;
  display: flex;
  gap: 16rpx;
  background: #ffffff;
  padding: 16rpx;
  border-radius: 16rpx;
  box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.06);
}

.park-map-icon-img {
  width: 36rpx;
  height: 36rpx;
  padding: 10rpx;
}

.park-info {
  flex: 1;
}

.title {
  font-size: 30rpx;
  font-weight: 700;
}

.row {
  margin-top: 8rpx;
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 24rpx;
}

.btn-primary {
  margin-top: 12rpx;
  height: 72rpx;
  background: #C02C38;
  color: #fff;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 26rpx;
}

.park-source-active {
  background-image: url('/static/assets/park/park-map-icon-select.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  width: 56rpx;
  height: 56rpx;
}
</style>
